<?php

class Page extends CActiveRecord
{
	/**
	 * The followings are the available columns in table 'pages':
	 * @var integer $id
	 * @var integer $part_id
	 * @var string $title
	 * @var string $alias
	 * @var string $icon
	 * @var string $price
	 * @var string $preamble
	 * @var string $preamble_marked
	 * @var string $text
	 * @var string $text_marked
	 * @var string $author
	 * @var string $created
	 */

	public $_icon;
	var $_sizes = array(
		'orig',
		'small'=>array(111,125),
		'normal'=>array(241,140),
		'big'=>array(500,600),
	);
	public $_tag = array();
	public $preid = 'page';

	/**
	 * Returns the static model of the specified AR class.
	 * @return Page the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'pages';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('preid, part_id, title, alias, text, text_marked, author, created', 'required'),
			array('part_id', 'numerical', 'integerOnly'=>true),
			array('price', 'numerical'),
			array('title, icon', 'length', 'max'=>255),
			array('alias', 'length', 'max'=>45),
			array('alias', 'unique'),
			array('alias', 'match', 'pattern'=>'/[0-9a-z\-]+/is'),
			array('author', 'length', 'max'=>80),
			array('preamble, preamble_marked, _tag','safe'),
			array('page_title, page_description, page_keywords', 'safe'),
			
			array('_icon', 'file', 'types'=>'jpg, gif, png, jpeg', 'maxSize' => 10490000, 'allowEmpty'=>true),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, part_id, title, alias, text, text_marked, author, created', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'part'=>array(self::BELONGS_TO, 'Part', 'part_id'),
			'tags'=>array(self::MANY_MANY, 'Tag', 'pages_tags(page_id, tag_id)'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'part_id' => 'Раздел',
			'title' => 'Название',
			'alias' => 'Псевдоним',
			'icon' => 'Картинка',
			'price' => 'Цена, руб.',
			'preamble' => 'Преамбула',
			'preamble_marked' => 'Обработанная преамбула',
			'text' => 'Текст',
			'text_marked' => 'Обработанный текст',
			'author' => 'Автор',
			'created' => 'Дата создания',
			'page_title' => 'Тайтл',
			'page_description' => 'Описание',
			'page_keywords' => 'Ключевые слова',
			
			'_icon' => 'Картинка',
			'_tag' => 'Тэги',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search($criteria = null)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		if($criteria == null)
			$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);

		$criteria->compare('part_id',$this->part_id);

		$criteria->compare('title',$this->title,true);

		$criteria->compare('alias',$this->alias,true);

		$criteria->compare('price',$this->price,true);
		
		$criteria->compare('text',$this->text,true);

		$criteria->compare('text_marked',$this->text_marked,true);

		$criteria->compare('author',$this->author,true);

		$criteria->compare('created',$this->created,true);

		return new CActiveDataProvider('Page', array(
			'criteria'=>$criteria,
		));
	}
	
	public function afterFind(){
		parent::afterFind();
		
		if(!empty($this->tags)){
			foreach($this->tags as $tag){
				$this->_tag[] = $tag->tag;
			}
		}
	}
	
	public function beforeValidate(){
		Yii::import('ext.markdown.*');
		$md = new EMarkdown;
		$this->text_marked = $md->transform($this->text);
		if($this->preamble)
			$this->preamble_marked = $md->transform($this->preamble);
			
		if(isset($_POST['delete_icon']) && $_POST['delete_icon']){
			$this->icon = null;
		}
		
		$this->uploadIcon();

		return parent::beforeValidate();
	}
	
	protected function uploadIcon(){
		if($icon = CUploadedFile::getInstance($this,'_icon')) {
			$filename = CString::strtolower($this->alias.'.'.$icon->extensionName);
			$path = Yii::getPathOfAlias( 'webroot.images.icon' ).DIRECTORY_SEPARATOR;

			$this->icon = Image::addFile( $icon, $filename, $path, $this->_sizes, $this->title, $this->title);
		}elseif(!empty($this->icon)){
			unset($this->icon);
		}
	}
	
	public function afterDelete(){
		$at = PagesTags::model()->findAll('page_id=:page_id',array(':page_id'=>$this->id));
		foreach($at as $item){
			// Если тега нет в возвращенных
			if($item->tag->frequency <= 1) {
				// Удаляю теги и связь у которых вес 1
				$item->tag->delete();
				$item->delete();
			} else {
				// Теги у которых вес больше 1, вычетаются единица и удаляется связь
				$item->tag->frequency -= 1;
				$item->tag->save();
				$item->delete();
			}
		}
		
		return parent::afterDelete();
	}
	
	public function afterSave(){
		$this->saveTag();
		return parent::afterSave();
	}

	protected function saveTag(){
		if($this->_tag){

			$at = PagesTags::model()->findAll('page_id=:page_id',array(':page_id'=>$this->id));

			foreach($at as $item){
				if(in_array($item->tag->tag, $this->_tag)){
					// Если тег есть в таблице и в возвращенных из формы то все остается по прежнему 
					continue;
				} else {
					// Если тега нет в возвращенных
					if($item->tag->frequency <= 1) {
						// Удаляю теги и связь у которых вес 1
						$item->tag->delete();
						$item->delete();
					} else {
						// Теги у которых вес больше 1, вычетаются единица и удаляется связь
						$item->tag->frequency -= 1;
						$item->tag->save();
						$item->delete();
					}
				}
			}
			
			foreach($this->_tag as $word){
				if($tag = Tag::model()->find('tag=:tag', array(':tag'=>$word))){
					if(!PagesTags::model()->exists('page_id=:page_id and tag_id=:tag_id', array(':page_id'=>$this->id, ':tag_id'=>$tag->id))){
						// Если тег в таблице есть но связи нет
						// добавляем связь и увеличиваем вес тега
						$PagesTags = new PagesTags;
						$PagesTags->page_id = $this->id;
						$PagesTags->tag_id = $tag->id;
						$PagesTags->save();
						#if(!empty($PagesTags->errors))d($PagesTags->errors);
							
						$tag->frequency += 1;
						$tag->save();
						#if(!empty($tag->errors))d($tag->errors);
						
					}
				} else {
					// Если тега нет в таблцице то добавляю тег и связь
					$tag = new Tag;
					$tag->tag = $word;
					$tag->frequency = 1;
					$tag->save();
					#if(!empty($tag->errors))d($tag->errors);
					$PagesTags = new PagesTags;
					$PagesTags->page_id = $this->id;
					$PagesTags->tag_id = $tag->id;
					$PagesTags->save();
					#if(!empty($PagesTags->errors))d($PagesTags->errors);
				}
			}
		}
	}
}